// pages/register/register.js
Page({
  data: {
    userName: null,
    firstPassword: null,
    secondPassword: null
  },
  setUserName(e){
    this.setData({
      userName: e.detail.value
    });
  },
  setFirstPassword(e) {
    this.setData({
      firstPassword: e.detail.value
    });
  },
  setSecondPassword(e) {
    this.setData({
      secondPassword: e.detail.value
    });
  },

  register() {
    // console.log(this.data.userName);
    // console.log(this.data.firstPassword);
    // console.log(this.data.secondPassword);
    if(!this.noExistNullValue()) {
      wx.showToast({
        title: '信息不完整',
        icon: "error", 
        duration: 2000,
      });
      return;
    }
    if(!this.passwordIsSame(this.data.firstPassword, this.data.secondPassword)) {
      wx.showToast({
        title: '密码不一致',
        icon: "error", 
        duration: 2000,
      });
      return;
    }
    if(!this.passwordIsLegal(this.data.firstPassword)) {
      wx.showToast({
        title: '密码长度>=6',
        icon: "error", 
        duration: 2000,
      });
      return;
    }
    var database = wx.cloud.database();
    if(!this.userIsUnique(database)) {
      return;
    }
    this.addUser(database);
  },
  noExistNullValue() {
    for (const key in this.data) {
      if (this.data[key] === null) {
        return false;
      }
    }
    return true;
  },
  passwordIsLegal(password) {
    return password.length >= 6;
  },
  addUser(database) {
    // if(database == null) {
    // }
    database.collection('user')
      .add({
        data: {
          name: this.data.userName,
          password: this.data.firstPassword
        }
      })
      .then(res => {
        console.log("新增成功：", res);
        wx.navigateBack();
        wx.showToast({
          title: '注册成功',
          icon: "success", 
          duration: 2000,
        });
      })
      .catch(err => {
        console.error("新增失败：", err);
      });
  },
  userIsUnique(database) {
    var isUnique = true;
    database.collection("user")
            .where({
              "name": this.data.userName,
            })
            .get()
            .then((res) => {
              isUnique = res.data.length == 0;
            });
    return isUnique;
  },
  passwordIsSame(first, second) {
    return first === second;
  }
})